(()=>{var e={21:function(e,t,i){var s;e.exports=(s=s||function(e,t){var s;if("undefined"!=typeof window&&window.crypto&&(s=window.crypto),"undefined"!=typeof self&&self.crypto&&(s=self.crypto),"undefined"!=typeof globalThis&&globalThis.crypto&&(s=globalThis.crypto),!s&&"undefined"!=typeof window&&window.msCrypto&&(s=window.msCrypto),!s&&void 0!==i.g&&i.g.crypto&&(s=i.g.crypto),!s)try{s=i(477)}catch(e){}var r=function(){if(s){if("function"==typeof s.getRandomValues)try{return s.getRandomValues(new Uint32Array(1))[0]}catch(e){}if("function"==typeof s.randomBytes)try{return s.randomBytes(4).readInt32LE()}catch(e){}}throw new Error("Native crypto module could not be used to get secure random number.")},n=Object.create||function(){function e(){}return function(t){var i;return e.prototype=t,i=new e,e.prototype=null,i}}(),o={},a=o.lib={},c=a.Base={extend:function(e){var t=n(this);return e&&t.mixIn(e),t.hasOwnProperty("init")&&this.init!==t.init||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},l=a.WordArray=c.extend({init:function(e,i){e=this.words=e||[],this.sigBytes=i!=t?i:4*e.length},toString:function(e){return(e||u).stringify(this)},concat:function(e){var t=this.words,i=e.words,s=this.sigBytes,r=e.sigBytes;if(this.clamp(),s%4)for(var n=0;n>>2]>>>24-n%4*8&255;t[s+n>>>2]|=o<<24-(s+n)%4*8}else for(var a=0;a>>2]=i[a>>>2];return this.sigBytes+=r,this},clamp:function(){var t=this.words,i=this.sigBytes;t[i>>>2]&=4294967295<<32-i%4*8,t.length=e.ceil(i/4)},clone:function(){var e=c.clone.call(this);return e.words=this.words.slice(0),e},random:function(e){for(var t=[],i=0;i>>2]>>>24-r%4*8&255;s.push((n>>>4).toString(16)),s.push((15&n).toString(16))}return s.join("")},parse:function(e){for(var t=e.length,i=[],s=0;s>>3]|=parseInt(e.substr(s,2),16)<<24-s%8*4;return new l.init(i,t/2)}},h=d.Latin1={stringify:function(e){for(var t=e.words,i=e.sigBytes,s=[],r=0;r>>2]>>>24-r%4*8&255;s.push(String.fromCharCode(n))}return s.join("")},parse:function(e){for(var t=e.length,i=[],s=0;s>>2]|=(255&e.charCodeAt(s))<<24-s%4*8;return new l.init(i,t)}},g=d.Utf8={stringify:function(e){try{return decodeURIComponent(escape(h.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return h.parse(unescape(encodeURIComponent(e)))}},p=a.BufferedBlockAlgorithm=c.extend({reset:function(){this._data=new l.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=g.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var i,s=this._data,r=s.words,n=s.sigBytes,o=this.blockSize,a=n/(4*o),c=(a=t?e.ceil(a):e.max((0|a)-this._minBufferSize,0))*o,d=e.min(4*c,n);if(c){for(var u=0;u>>6-o%4*2;r[n>>>2]|=a<<24-n%4*8,n++}return t.create(r,n)}e.enc.Base64={stringify:function(e){var t=e.words,i=e.sigBytes,s=this._map;e.clamp();for(var r=[],n=0;n>>2]>>>24-n%4*8&255)<<16|(t[n+1>>>2]>>>24-(n+1)%4*8&255)<<8|t[n+2>>>2]>>>24-(n+2)%4*8&255,a=0;a<4&&n+.75*a>>6*(3-a)&63));var c=s.charAt(64);if(c)for(;r.length%4;)r.push(c);return r.join("")},parse:function(e){var t=e.length,s=this._map,r=this._reverseMap;if(!r){r=this._reverseMap=[];for(var n=0;n>>7)^(p<<14|p>>>18)^p>>>3,w=l[g-2],f=(w<<15|w>>>17)^(w<<13|w>>>19)^w>>>10;l[g]=_+l[g-7]+f+l[g-16]}var m=s&r^s&n^r&n,y=(s<<30|s>>>2)^(s<<19|s>>>13)^(s<<10|s>>>22),b=h+((a<<26|a>>>6)^(a<<21|a>>>11)^(a<<7|a>>>25))+(a&d^~a&u)+c[g]+l[g];h=u,u=d,d=a,a=o+b|0,o=n,n=r,r=s,s=b+(y+m)|0}i[0]=i[0]+s|0,i[1]=i[1]+r|0,i[2]=i[2]+n|0,i[3]=i[3]+o|0,i[4]=i[4]+a|0,i[5]=i[5]+d|0,i[6]=i[6]+u|0,i[7]=i[7]+h|0},_doFinalize:function(){var t=this._data,i=t.words,s=8*this._nDataBytes,r=8*t.sigBytes;return i[r>>>5]|=128<<24-r%32,i[14+(r+64>>>9<<4)]=e.floor(s/4294967296),i[15+(r+64>>>9<<4)]=s,t.sigBytes=4*i.length,this._process(),this._hash},clone:function(){var e=n.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=n._createHelper(d),t.HmacSHA256=n._createHmacHelper(d)}(Math),s.SHA256)},65:function(e,t,i){var s,r; /* * loglevel - https://github.com/pimterry/loglevel * * Copyright (c) 2013 Tim Perry * Licensed under the MIT license. */!function(){"use strict";s=function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],r={},n=null;function o(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch(t){return function(){return Function.prototype.apply.apply(i,[e,arguments])}}}function a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(s){return"debug"===s&&(s="log"),typeof console!==t&&("trace"===s&&i?a:void 0!==console[s]?o(console,s):void 0!==console.log?o(console,"log"):e)}function l(){for(var i=this.getLevel(),r=0;r=0&&t<=d.levels.SILENT)return t;throw new TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?h+=":"+e:"symbol"==typeof e&&(h=void 0),d.name=e,d.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},d.methodFactory=i||u,d.getLevel=function(){return null!=c?c:null!=a?a:o},d.setLevel=function(e,t){return c=w(e),!1!==t&&g(c),l.call(d)},d.setDefaultLevel=function(e){a=w(e),p()||d.setLevel(e,!1)},d.resetLevel=function(){c=null,_(),l.call(d)},d.enableAll=function(e){d.setLevel(d.levels.TRACE,e)},d.disableAll=function(e){d.setLevel(d.levels.SILENT,e)},d.rebuild=function(){if(n!==d&&(o=w(n.getLevel())),l.call(d),n===d)for(var e in r)r[e].rebuild()},o=w(n?n.getLevel():"WARN");var f=p();null!=f&&(c=w(f)),l.call(d)}(n=new h).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=r[e];return t||(t=r[e]=new h(e,n.methodFactory)),t};var g=typeof window!==t?window.log:void 0;return n.noConflict=function(){return typeof window!==t&&window.log===n&&(window.log=g),n},n.getLoggers=function(){return r},n.default=n,n},void 0===(r="function"==typeof s?s.call(t,i,t,e):s)||(e.exports=r)}()},477:()=>{}},t={};function i(s){var r=t[s];if(void 0!==r)return r.exports;var n=t[s]={exports:{}};return e[s].call(n.exports,n,n.exports,i),n.exports}i.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return i.d(t,{a:t}),t},i.d=(e,t)=>{for(var s in t)i.o(t,s)&&!i.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},i.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{"use strict";let e;!function(e){e.IdwHydraHasErrorKey="IDW_HYDRA_HAS_ERROR",e.IdwCohortIdsKey="cohort_ids",e.idwScrollY="idw-scroll-y",e.IdwImpressionsKey="idw-impressions",e.anonymised="Anonymised",e.isOofUrl="idw-oof",e.idwOutdated="idw-outdated",e.AnonSignalLift="anon-sl",e.AnonSignalLiftGroup="anon-sl-group",e.AnonSignalLiftGroupNoUser="anon-sl-group-no-user",e.AnonSignalLiftGroupTimestamp="anon-sl-group-ts",e.AnonSignalLiftGroupSession="anon-sl-group-session",e.AnonUserSync="anon-hndshk",e.AnonAudienceMemberId="anon-audience-member",e.AnonAudienceMeta="anon-audiences-meta",e.AnonAudienceGoogle="anon-audiences-google"}(e||(e={}));var t=i(21),s=i(9),r=i(754),n=i(178);function o(e){this.message=e}o.prototype=new Error,o.prototype.name="InvalidCharacterError";var a="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(e){var t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new o("'atob' failed: The string to be decoded is not correctly encoded.");for(var i,s,r=0,n=0,a="";s=t.charAt(n++);~s&&(i=r%4?64*i+s:s,r++%4)?a+=String.fromCharCode(255&i>>(-2*r&6)):0)s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(s);return a};function c(e){var t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(a(e).replace(/(.)/g,(function(e,t){var i=t.charCodeAt(0).toString(16).toUpperCase();return i.length<2&&(i="0"+i),"%"+i})))}(t)}catch(e){return a(t)}}function l(e){this.message=e}l.prototype=new Error,l.prototype.name="InvalidTokenError";const d=function(e,t){if("string"!=typeof e)throw new l("Invalid token specified");var i=!0===(t=t||{}).header?0:1;try{return JSON.parse(c(e.split(".")[i]))}catch(e){throw new l("Invalid token specified: "+e.message)}};var u,h,g,p={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},_=(e=>(e[e.NONE=0]="NONE",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG",e))(_||{});(g=_||(_={})).reset=function(){u=3,h=p},g.setLevel=function(e){if(!(0<=e&&e<=4))throw new Error("Invalid log level");u=e},g.setLogger=function(e){h=e};var w=class{constructor(e){this._name=e}debug(...e){u>=4&&h.debug(w._format(this._name,this._method),...e)}info(...e){u>=3&&h.info(w._format(this._name,this._method),...e)}warn(...e){u>=2&&h.warn(w._format(this._name,this._method),...e)}error(...e){u>=1&&h.error(w._format(this._name,this._method),...e)}throw(e){throw this.error(e),e}create(e){const t=Object.create(this);return t._method=e,t.debug("begin"),t}static createStatic(e,t){const i=new w(`${e}.${t}`);return i.debug("begin"),i}static _format(e,t){const i=`[${e}]`;return t?`${i} ${t}:`:i}static debug(e,...t){u>=4&&h.debug(w._format(e),...t)}static info(e,...t){u>=3&&h.info(w._format(e),...t)}static warn(e,...t){u>=2&&h.warn(w._format(e),...t)}static error(e,...t){u>=1&&h.error(w._format(e),...t)}};_.reset();var f=class{static _randomWord(){return t.lib.WordArray.random(1).words[0]}static generateUUIDv4(){return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(e=>(+e^f._randomWord()&15>>+e/4).toString(16))).replace(/-/g,"")}static generateCodeVerifier(){return f.generateUUIDv4()+f.generateUUIDv4()+f.generateUUIDv4()}static generateCodeChallenge(e){try{const t=s(e);return r.stringify(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(e){throw w.error("CryptoUtils.generateCodeChallenge",e),e}}static generateBasicAuth(e,t){const i=n.parse([e,t].join(":"));return r.stringify(i)}},m=class{constructor(e){this._name=e,this._logger=new w(`Event('${this._name}')`),this._callbacks=[]}addHandler(e){return this._callbacks.push(e),()=>this.removeHandler(e)}removeHandler(e){const t=this._callbacks.lastIndexOf(e);t>=0&&this._callbacks.splice(t,1)}raise(...e){this._logger.debug("raise:",...e);for(const t of this._callbacks)t(...e)}},y=class{static decode(e){try{return d(e)}catch(e){throw w.error("JwtUtils.decode",e),e}}},b=class{static center({...e}){var t;return null==e.width&&(e.width=null!=(t=[800,720,600,480].find((e=>e<=window.outerWidth/1.618)))?t:360),null!=e.left||(e.left=Math.max(0,Math.round(window.screenX+(window.outerWidth-e.width)/2))),null!=e.height&&(null!=e.top||(e.top=Math.max(0,Math.round(window.screenY+(window.outerHeight-e.height)/2)))),e}static serialize(e){return Object.entries(e).filter((([,e])=>null!=e)).map((([e,t])=>`${e}=${"boolean"!=typeof t?t:t?"yes":"no"}`)).join(",")}},v=class extends m{constructor(){super(...arguments),this._logger=new w(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{const e=this._expiration-v.getEpochTime();this._logger.debug("timer completes in",e),this._expiration<=v.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(e){const t=this._logger.create("init");e=Math.max(Math.floor(e),1);const i=v.getEpochTime()+e;if(this.expiration===i&&this._timerHandle)return void t.debug("skipping since already initialized for expiration at",this.expiration);this.cancel(),t.debug("using duration",e),this._expiration=i;const s=Math.min(e,5);this._timerHandle=setInterval(this._callback,1e3*s)}get expiration(){return this._expiration}cancel(){this._logger.create("cancel"),this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}},S=class{static readParams(e,t="query"){if(!e)throw new TypeError("Invalid URL");const i=new URL(e,window.location.origin)["fragment"===t?"hash":"search"];return new URLSearchParams(i.slice(1))}},k=class extends Error{constructor(e,t){var i,s,r;if(super(e.error_description||e.error||""),this.form=t,this.name="ErrorResponse",!e.error)throw w.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=e.error,this.error_description=null!=(i=e.error_description)?i:null,this.error_uri=null!=(s=e.error_uri)?s:null,this.state=e.userState,this.session_state=null!=(r=e.session_state)?r:null}},T=class extends Error{constructor(e){super(e),this.name="ErrorTimeout"}},I=class{constructor(e){this._logger=new w("AccessTokenEvents"),this._expiringTimer=new v("Access token expiring"),this._expiredTimer=new v("Access token expired"),this._expiringNotificationTimeInSeconds=e.expiringNotificationTimeInSeconds}load(e){const t=this._logger.create("load");if(e.access_token&&void 0!==e.expires_in){const i=e.expires_in;if(t.debug("access token present, remaining duration:",i),i>0){let e=i-this._expiringNotificationTimeInSeconds;e<=0&&(e=1),t.debug("registering expiring timer, raising in",e,"seconds"),this._expiringTimer.init(e)}else t.debug("canceling existing expiring timer because we're past expiration."),this._expiringTimer.cancel();const s=i+1;t.debug("registering expired timer, raising in",s,"seconds"),this._expiredTimer.init(s)}else this._expiringTimer.cancel(),this._expiredTimer.cancel()}unload(){this._logger.debug("unload: canceling existing access token timers"),this._expiringTimer.cancel(),this._expiredTimer.cancel()}addAccessTokenExpiring(e){return this._expiringTimer.addHandler(e)}removeAccessTokenExpiring(e){this._expiringTimer.removeHandler(e)}addAccessTokenExpired(e){return this._expiredTimer.addHandler(e)}removeAccessTokenExpired(e){this._expiredTimer.removeHandler(e)}},C=class{constructor(e,t,i,s,r){this._callback=e,this._client_id=t,this._intervalInSeconds=s,this._stopOnError=r,this._logger=new w("CheckSessionIFrame"),this._timer=null,this._session_state=null,this._message=e=>{e.origin===this._frame_origin&&e.source===this._frame.contentWindow&&("error"===e.data?(this._logger.error("error message from check session op iframe"),this._stopOnError&&this.stop()):"changed"===e.data?(this._logger.debug("changed message from check session op iframe"),this.stop(),this._callback()):this._logger.debug(e.data+" message from check session op iframe"))};const n=new URL(i);this._frame_origin=n.origin,this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="fixed",this._frame.style.left="-1000px",this._frame.style.top="0",this._frame.width="0",this._frame.height="0",this._frame.src=n.href}load(){return new Promise((e=>{this._frame.onload=()=>{e()},window.document.body.appendChild(this._frame),window.addEventListener("message",this._message,!1)}))}start(e){if(this._session_state===e)return;this._logger.create("start"),this.stop(),this._session_state=e;const t=()=>{this._frame.contentWindow&&this._session_state&&this._frame.contentWindow.postMessage(this._client_id+" "+this._session_state,this._frame_origin)};t(),this._timer=setInterval(t,1e3*this._intervalInSeconds)}stop(){this._logger.create("stop"),this._session_state=null,this._timer&&(clearInterval(this._timer),this._timer=null)}},E=class{constructor(){this._logger=new w("InMemoryWebStorage"),this._data={}}clear(){this._logger.create("clear"),this._data={}}getItem(e){return this._logger.create(`getItem('${e}')`),this._data[e]}setItem(e,t){this._logger.create(`setItem('${e}')`),this._data[e]=t}removeItem(e){this._logger.create(`removeItem('${e}')`),delete this._data[e]}get length(){return Object.getOwnPropertyNames(this._data).length}key(e){return Object.getOwnPropertyNames(this._data)[e]}},x=class{constructor(e=[],t=null){this._jwtHandler=t,this._logger=new w("JsonService"),this._contentTypes=[],this._contentTypes.push(...e,"application/json"),t&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(e,t={}){const{timeoutInSeconds:i,...s}=t;if(!i)return await fetch(e,s);const r=new AbortController,n=setTimeout((()=>r.abort()),1e3*i);try{return await fetch(e,{...t,signal:r.signal})}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)throw new T("Network timed out");throw e}finally{clearTimeout(n)}}async getJson(e,{token:t,credentials:i}={}){const s=this._logger.create("getJson"),r={Accept:this._contentTypes.join(", ")};let n;t&&(s.debug("token passed, setting Authorization header"),r.Authorization="Bearer "+t);try{s.debug("url:",e),n=await this.fetchWithTimeout(e,{method:"GET",headers:r,credentials:i})}catch(e){throw s.error("Network Error"),e}s.debug("HTTP response received, status",n.status);const o=n.headers.get("Content-Type");if(o&&!this._contentTypes.find((e=>o.startsWith(e)))&&s.throw(new Error(`Invalid response Content-Type: ${null!=o?o:"undefined"}, from URL: ${e}`)),n.ok&&this._jwtHandler&&(null==o?void 0:o.startsWith("application/jwt")))return await this._jwtHandler(await n.text());let a;try{a=await n.json()}catch(e){if(s.error("Error parsing JSON response",e),n.ok)throw e;throw new Error(`${n.statusText} (${n.status})`)}if(!n.ok){if(s.error("Error from server:",a),a.error)throw new k(a);throw new Error(`${n.statusText} (${n.status}): ${JSON.stringify(a)}`)}return a}async postForm(e,{body:t,basicAuth:i,timeoutInSeconds:s,initCredentials:r}){const n=this._logger.create("postForm"),o={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded"};let a;void 0!==i&&(o.Authorization="Basic "+i);try{n.debug("url:",e),a=await this.fetchWithTimeout(e,{method:"POST",headers:o,body:t,timeoutInSeconds:s,credentials:r})}catch(e){throw n.error("Network error"),e}n.debug("HTTP response received, status",a.status);const c=a.headers.get("Content-Type");if(c&&!this._contentTypes.find((e=>c.startsWith(e))))throw new Error(`Invalid response Content-Type: ${null!=c?c:"undefined"}, from URL: ${e}`);const l=await a.text();let d={};if(l)try{d=JSON.parse(l)}catch(e){if(n.error("Error parsing JSON response",e),a.ok)throw e;throw new Error(`${a.statusText} (${a.status})`)}if(!a.ok){if(n.error("Error from server:",d),d.error)throw new k(d,t);throw new Error(`${a.statusText} (${a.status}): ${JSON.stringify(d)}`)}return d}},R=class{constructor(e){this._settings=e,this._logger=new w("MetadataService"),this._jsonService=new x(["application/jwk-set+json"]),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._settings.signingKeys&&(this._logger.debug("using signingKeys from settings"),this._signingKeys=this._settings.signingKeys),this._settings.metadata&&(this._logger.debug("using metadata from settings"),this._metadata=this._settings.metadata),this._settings.fetchRequestCredentials&&(this._logger.debug("using fetchRequestCredentials from settings"),this._fetchRequestCredentials=this._settings.fetchRequestCredentials)}resetSigningKeys(){this._signingKeys=null}async getMetadata(){const e=this._logger.create("getMetadata");if(this._metadata)return e.debug("using cached values"),this._metadata;if(!this._metadataUrl)throw e.throw(new Error("No authority or metadataUrl configured on settings")),null;e.debug("getting metadata from",this._metadataUrl);const t=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials});return e.debug("merging remote JSON with seed metadata"),this._metadata=Object.assign({},this._settings.metadataSeed,t),this._metadata}getIssuer(){return this._getMetadataProperty("issuer")}getAuthorizationEndpoint(){return this._getMetadataProperty("authorization_endpoint")}getUserInfoEndpoint(){return this._getMetadataProperty("userinfo_endpoint")}getTokenEndpoint(e=!0){return this._getMetadataProperty("token_endpoint",e)}getCheckSessionIframe(){return this._getMetadataProperty("check_session_iframe",!0)}getEndSessionEndpoint(){return this._getMetadataProperty("end_session_endpoint",!0)}getRevocationEndpoint(e=!0){return this._getMetadataProperty("revocation_endpoint",e)}getKeysEndpoint(e=!0){return this._getMetadataProperty("jwks_uri",e)}async _getMetadataProperty(e,t=!1){const i=this._logger.create(`_getMetadataProperty('${e}')`),s=await this.getMetadata();if(i.debug("resolved"),void 0===s[e]){if(!0===t)return void i.warn("Metadata does not contain optional property");i.throw(new Error("Metadata does not contain property "+e))}return s[e]}async getSigningKeys(){const e=this._logger.create("getSigningKeys");if(this._signingKeys)return e.debug("returning signingKeys from cache"),this._signingKeys;const t=await this.getKeysEndpoint(!1);e.debug("got jwks_uri",t);const i=await this._jsonService.getJson(t);if(e.debug("got key set",i),!Array.isArray(i.keys))throw e.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=i.keys,this._signingKeys}},U=class{constructor({prefix:e="oidc.",store:t=localStorage}={}){this._logger=new w("WebStorageStateStore"),this._store=t,this._prefix=e}async set(e,t){this._logger.create(`set('${e}')`),e=this._prefix+e,await this._store.setItem(e,t)}async get(e){this._logger.create(`get('${e}')`),e=this._prefix+e;return await this._store.getItem(e)}async remove(e){this._logger.create(`remove('${e}')`),e=this._prefix+e;const t=await this._store.getItem(e);return await this._store.removeItem(e),t}async getAllKeys(){this._logger.create("getAllKeys");const e=await this._store.length,t=[];for(let i=0;i{const t=this._logger.create("_getClaimsFromJwt");try{const i=y.decode(e);return t.debug("JWT decoding successful"),i}catch(e){throw t.error("Error parsing JWT response"),e}},this._jsonService=new x(void 0,this._getClaimsFromJwt)}async getClaims(e){const t=this._logger.create("getClaims");e||this._logger.throw(new Error("No token passed"));const i=await this._metadataService.getUserInfoEndpoint();t.debug("got userinfo url",i);const s=await this._jsonService.getJson(i,{token:e,credentials:this._settings.fetchRequestCredentials});return t.debug("got claims",s),s}},P=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new w("TokenClient"),this._jsonService=new x(this._settings.revokeTokenAdditionalContentTypes)}async exchangeCode({grant_type:e="authorization_code",redirect_uri:t=this._settings.redirect_uri,client_id:i=this._settings.client_id,client_secret:s=this._settings.client_secret,...r}){const n=this._logger.create("exchangeCode");i||n.throw(new Error("A client_id is required")),t||n.throw(new Error("A redirect_uri is required")),r.code||n.throw(new Error("A code is required"));const o=new URLSearchParams({grant_type:e,redirect_uri:t});for(const[e,t]of Object.entries(r))null!=t&&o.set(e,t);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(!s)throw n.throw(new Error("A client_secret is required")),null;a=f.generateBasicAuth(i,s);break;case"client_secret_post":o.append("client_id",i),s&&o.append("client_secret",s)}const c=await this._metadataService.getTokenEndpoint(!1);n.debug("got token endpoint");const l=await this._jsonService.postForm(c,{body:o,basicAuth:a,initCredentials:this._settings.fetchRequestCredentials});return n.debug("got response"),l}async exchangeCredentials({grant_type:e="password",client_id:t=this._settings.client_id,client_secret:i=this._settings.client_secret,scope:s=this._settings.scope,...r}){const n=this._logger.create("exchangeCredentials");t||n.throw(new Error("A client_id is required"));const o=new URLSearchParams({grant_type:e,scope:s});for(const[e,t]of Object.entries(r))null!=t&&o.set(e,t);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(!i)throw n.throw(new Error("A client_secret is required")),null;a=f.generateBasicAuth(t,i);break;case"client_secret_post":o.append("client_id",t),i&&o.append("client_secret",i)}const c=await this._metadataService.getTokenEndpoint(!1);n.debug("got token endpoint");const l=await this._jsonService.postForm(c,{body:o,basicAuth:a,initCredentials:this._settings.fetchRequestCredentials});return n.debug("got response"),l}async exchangeRefreshToken({grant_type:e="refresh_token",client_id:t=this._settings.client_id,client_secret:i=this._settings.client_secret,timeoutInSeconds:s,...r}){const n=this._logger.create("exchangeRefreshToken");t||n.throw(new Error("A client_id is required")),r.refresh_token||n.throw(new Error("A refresh_token is required"));const o=new URLSearchParams({grant_type:e});for(const[e,t]of Object.entries(r))null!=t&&o.set(e,t);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(!i)throw n.throw(new Error("A client_secret is required")),null;a=f.generateBasicAuth(t,i);break;case"client_secret_post":o.append("client_id",t),i&&o.append("client_secret",i)}const c=await this._metadataService.getTokenEndpoint(!1);n.debug("got token endpoint");const l=await this._jsonService.postForm(c,{body:o,basicAuth:a,timeoutInSeconds:s,initCredentials:this._settings.fetchRequestCredentials});return n.debug("got response"),l}async revoke(e){var t;const i=this._logger.create("revoke");e.token||i.throw(new Error("A token is required"));const s=await this._metadataService.getRevocationEndpoint(!1);i.debug(`got revocation endpoint, revoking ${null!=(t=e.token_type_hint)?t:"default token type"}`);const r=new URLSearchParams;for(const[t,i]of Object.entries(e))null!=i&&r.set(t,i);r.set("client_id",this._settings.client_id),this._settings.client_secret&&r.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(s,{body:r}),i.debug("got response")}},M=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],L=["sub","iss","aud","exp","iat"],N=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new w("ResponseValidator"),this._userInfoService=new O(this._settings,this._metadataService),this._tokenClient=new P(this._settings,this._metadataService)}async validateSigninResponse(e,t){const i=this._logger.create("validateSigninResponse");this._processSigninState(e,t),i.debug("state processed"),await this._processCode(e,t),i.debug("code processed"),e.isOpenId&&this._validateIdTokenAttributes(e),i.debug("tokens validated"),await this._processClaims(e,null==t?void 0:t.skipUserInfo,e.isOpenId),i.debug("claims processed")}async validateCredentialsResponse(e,t){const i=this._logger.create("validateCredentialsResponse");e.isOpenId&&this._validateIdTokenAttributes(e),i.debug("tokens validated"),await this._processClaims(e,t,e.isOpenId),i.debug("claims processed")}async validateRefreshResponse(e,t){const i=this._logger.create("validateRefreshResponse");e.userState=t.data,null!=e.session_state||(e.session_state=t.session_state),null!=e.scope||(e.scope=t.scope),e.isOpenId&&e.id_token&&(this._validateIdTokenAttributes(e,t.id_token),i.debug("ID Token validated")),e.id_token||(e.id_token=t.id_token,e.profile=t.profile);const s=e.isOpenId&&!!e.id_token;await this._processClaims(e,!1,s),i.debug("claims processed")}validateSignoutResponse(e,t){const i=this._logger.create("validateSignoutResponse");if(t.id!==e.state&&i.throw(new Error("State does not match")),i.debug("state validated"),e.userState=t.data,e.error)throw i.warn("Response was error",e.error),new k(e)}_processSigninState(e,t){const i=this._logger.create("_processSigninState");if(t.id!==e.state&&i.throw(new Error("State does not match")),t.client_id||i.throw(new Error("No client_id on state")),t.authority||i.throw(new Error("No authority on state")),this._settings.authority!==t.authority&&i.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==t.client_id&&i.throw(new Error("client_id mismatch on settings vs. signin state")),i.debug("state validated"),e.userState=t.data,null!=e.scope||(e.scope=t.scope),e.error)throw i.warn("Response was error",e.error),new k(e);t.code_verifier&&!e.code&&i.throw(new Error("Expected code in response"))}async _processClaims(e,t=!1,i=!0){const s=this._logger.create("_processClaims");if(e.profile=this._filterProtocolClaims(e.profile),t||!this._settings.loadUserInfo||!e.access_token)return void s.debug("not loading user info");s.debug("loading user info");const r=await this._userInfoService.getClaims(e.access_token);s.debug("user info claims received from user info endpoint"),i&&r.sub!==e.profile.sub&&s.throw(new Error("subject from UserInfo response does not match subject in ID Token")),e.profile=this._mergeClaims(e.profile,this._filterProtocolClaims(r)),s.debug("user info claims received, updated profile:",e.profile)}_mergeClaims(e,t){const i={...e};for(const[e,s]of Object.entries(t))for(const t of Array.isArray(s)?s:[s]){const s=i[e];s?Array.isArray(s)?s.includes(t)||s.push(t):i[e]!==t&&("object"==typeof t&&this._settings.mergeClaims?i[e]=this._mergeClaims(s,t):i[e]=[s,t]):i[e]=t}return i}_filterProtocolClaims(e){const t={...e};if(this._settings.filterProtocolClaims){let e;e=Array.isArray(this._settings.filterProtocolClaims)?this._settings.filterProtocolClaims:M;for(const i of e)L.includes(i)||delete t[i]}return t}async _processCode(e,t){const i=this._logger.create("_processCode");if(e.code){i.debug("Validating code");const s=await this._tokenClient.exchangeCode({client_id:t.client_id,client_secret:t.client_secret,code:e.code,redirect_uri:t.redirect_uri,code_verifier:t.code_verifier,...t.extraTokenParams});Object.assign(e,s)}else i.debug("No code to process")}_validateIdTokenAttributes(e,t){var i;const s=this._logger.create("_validateIdTokenAttributes");s.debug("decoding ID Token JWT");const r=y.decode(null!=(i=e.id_token)?i:"");if(r.sub||s.throw(new Error("ID Token is missing a subject claim")),t){const e=y.decode(t);e.sub!==r.sub&&s.throw(new Error("sub in id_token does not match current sub")),e.auth_time&&e.auth_time!==r.auth_time&&s.throw(new Error("auth_time in id_token does not match original auth_time")),e.azp&&e.azp!==r.azp&&s.throw(new Error("azp in id_token does not match original azp")),!e.azp&&r.azp&&s.throw(new Error("azp not in id_token, but present in original id_token"))}e.profile=r}},q=class{constructor(e){this.id=e.id||f.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=v.getEpochTime(),this.request_type=e.request_type}toStorageString(){return new w("State").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type})}static fromStorageString(e){return w.createStatic("State","fromStorageString"),new q(JSON.parse(e))}static async clearStaleState(e,t){const i=w.createStatic("State","clearStaleState"),s=v.getEpochTime()-t,r=await e.getAllKeys();i.debug("got keys",r);for(let t=0;tm.searchParams.append("resource",e)))}for(const[e,t]of Object.entries({response_mode:a,...f,...g}))null!=t&&m.searchParams.append(e,t.toString());this.url=m.href}},F=class{constructor(e){this.access_token="",this.token_type="",this.profile={},this.state=e.get("state"),this.session_state=e.get("session_state"),this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri"),this.code=e.get("code")}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-v.getEpochTime()}set expires_in(e){"string"==typeof e&&(e=Number(e)),void 0!==e&&e>=0&&(this.expires_at=Math.floor(e)+v.getEpochTime())}get isOpenId(){var e;return(null==(e=this.scope)?void 0:e.split(" ").includes("openid"))||!!this.id_token}},$=class{constructor({url:e,state_data:t,id_token_hint:i,post_logout_redirect_uri:s,extraQueryParams:r,request_type:n}){if(this._logger=new w("SignoutRequest"),!e)throw this._logger.error("ctor: No url passed"),new Error("url");const o=new URL(e);i&&o.searchParams.append("id_token_hint",i),s&&(o.searchParams.append("post_logout_redirect_uri",s),t&&(this.state=new q({data:t,request_type:n}),o.searchParams.append("state",this.state.id)));for(const[e,t]of Object.entries({...r}))null!=t&&o.searchParams.append(e,t.toString());this.url=o.href}},W=class{constructor(e){this.state=e.get("state"),this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri")}},z=class{constructor(e){this._logger=new w("OidcClient"),this.settings=new A(e),this.metadataService=new R(this.settings),this._validator=new N(this.settings,this.metadataService),this._tokenClient=new P(this.settings,this.metadataService)}async createSigninRequest({state:e,request:t,request_uri:i,request_type:s,id_token_hint:r,login_hint:n,skipUserInfo:o,nonce:a,response_type:c=this.settings.response_type,scope:l=this.settings.scope,redirect_uri:d=this.settings.redirect_uri,prompt:u=this.settings.prompt,display:h=this.settings.display,max_age:g=this.settings.max_age,ui_locales:p=this.settings.ui_locales,acr_values:_=this.settings.acr_values,resource:w=this.settings.resource,response_mode:f=this.settings.response_mode,extraQueryParams:m=this.settings.extraQueryParams,extraTokenParams:y=this.settings.extraTokenParams}){const b=this._logger.create("createSigninRequest");if("code"!==c)throw new Error("Only the Authorization Code flow (with PKCE) is supported");const v=await this.metadataService.getAuthorizationEndpoint();b.debug("Received authorization endpoint",v);const S=new H({url:v,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:d,response_type:c,scope:l,state_data:e,prompt:u,display:h,max_age:g,ui_locales:p,id_token_hint:r,login_hint:n,acr_values:_,resource:w,request:t,request_uri:i,extraQueryParams:m,extraTokenParams:y,request_type:s,response_mode:f,client_secret:this.settings.client_secret,skipUserInfo:o,nonce:a,disablePKCE:this.settings.disablePKCE});await this.clearStaleState();const k=S.state;return await this.settings.stateStore.set(k.id,k.toStorageString()),S}async readSigninResponseState(e,t=!1){const i=this._logger.create("readSigninResponseState"),s=new F(S.readParams(e,this.settings.response_mode));if(!s.state)throw i.throw(new Error("No state in response")),null;const r=await this.settings.stateStore[t?"remove":"get"](s.state);if(!r)throw i.throw(new Error("No matching state found in storage")),null;return{state:j.fromStorageString(r),response:s}}async processSigninResponse(e){const t=this._logger.create("processSigninResponse"),{state:i,response:s}=await this.readSigninResponseState(e,!0);return t.debug("received state from storage; validating response"),await this._validator.validateSigninResponse(s,i),s}async processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:i=!1,extraTokenParams:s={}}){const r=await this._tokenClient.exchangeCredentials({username:e,password:t,...s}),n=new F(new URLSearchParams);return Object.assign(n,r),await this._validator.validateCredentialsResponse(n,i),n}async useRefreshToken({state:e,timeoutInSeconds:t}){var i;const s=this._logger.create("useRefreshToken");let r;if(void 0===this.settings.refreshTokenAllowedScope)r=e.scope;else{const t=this.settings.refreshTokenAllowedScope.split(" ");r=((null==(i=e.scope)?void 0:i.split(" "))||[]).filter((e=>t.includes(e))).join(" ")}const n=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:r,timeoutInSeconds:t}),o=new F(new URLSearchParams);return Object.assign(o,n),s.debug("validating response",o),await this._validator.validateRefreshResponse(o,{...e,scope:r}),o}async createSignoutRequest({state:e,id_token_hint:t,request_type:i,post_logout_redirect_uri:s=this.settings.post_logout_redirect_uri,extraQueryParams:r=this.settings.extraQueryParams}={}){const n=this._logger.create("createSignoutRequest"),o=await this.metadataService.getEndSessionEndpoint();if(!o)throw n.throw(new Error("No end session endpoint")),null;n.debug("Received end session endpoint",o);const a=new $({url:o,id_token_hint:t,post_logout_redirect_uri:s,state_data:e,extraQueryParams:r,request_type:i});await this.clearStaleState();const c=a.state;return c&&(n.debug("Signout request has state to persist"),await this.settings.stateStore.set(c.id,c.toStorageString())),a}async readSignoutResponseState(e,t=!1){const i=this._logger.create("readSignoutResponseState"),s=new W(S.readParams(e,this.settings.response_mode));if(!s.state){if(i.debug("No state in response"),s.error)throw i.warn("Response was error:",s.error),new k(s);return{state:void 0,response:s}}const r=await this.settings.stateStore[t?"remove":"get"](s.state);if(!r)throw i.throw(new Error("No matching state found in storage")),null;return{state:q.fromStorageString(r),response:s}}async processSignoutResponse(e){const t=this._logger.create("processSignoutResponse"),{state:i,response:s}=await this.readSignoutResponseState(e,!0);return i?(t.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(s,i)):t.debug("No state from storage; skipping response validation"),s}clearStaleState(){return this._logger.create("clearStaleState"),q.clearStaleState(this.settings.stateStore,this.settings.staleStateAgeInSeconds)}async revokeToken(e,t){return this._logger.create("revokeToken"),await this._tokenClient.revoke({token:e,token_type_hint:t})}},B=class{constructor(e){this._userManager=e,this._logger=new w("SessionMonitor"),this._start=async e=>{const t=e.session_state;if(!t)return;const i=this._logger.create("_start");if(e.profile?(this._sub=e.profile.sub,this._sid=e.profile.sid,i.debug("session_state",t,", sub",this._sub)):(this._sub=void 0,this._sid=void 0,i.debug("session_state",t,", anonymous user")),this._checkSessionIFrame)this._checkSessionIFrame.start(t);else try{const e=await this._userManager.metadataService.getCheckSessionIframe();if(e){i.debug("initializing check session iframe");const s=this._userManager.settings.client_id,r=this._userManager.settings.checkSessionIntervalInSeconds,n=this._userManager.settings.stopCheckSessionOnError,o=new C(this._callback,s,e,r,n);await o.load(),this._checkSessionIFrame=o,o.start(t)}else i.warn("no check session iframe found in the metadata")}catch(e){i.error("Error from getCheckSessionIframe:",e instanceof Error?e.message:e)}},this._stop=()=>{const e=this._logger.create("_stop");if(this._sub=void 0,this._sid=void 0,this._checkSessionIFrame&&this._checkSessionIFrame.stop(),this._userManager.settings.monitorAnonymousSession){const t=setInterval((async()=>{clearInterval(t);try{const e=await this._userManager.querySessionStatus();if(e){const t={session_state:e.session_state,profile:e.sub&&e.sid?{sub:e.sub,sid:e.sid}:null};this._start(t)}}catch(t){e.error("error from querySessionStatus",t instanceof Error?t.message:t)}}),1e3)}},this._callback=async()=>{const e=this._logger.create("_callback");try{const t=await this._userManager.querySessionStatus();let i=!0;t&&this._checkSessionIFrame?t.sub===this._sub?(i=!1,this._checkSessionIFrame.start(t.session_state),t.sid===this._sid?e.debug("same sub still logged in at OP, restarting check session iframe; session_state",t.session_state):(e.debug("same sub still logged in at OP, session state has changed, restarting check session iframe; session_state",t.session_state),this._userManager.events._raiseUserSessionChanged())):e.debug("different subject signed into OP",t.sub):e.debug("subject no longer signed into OP"),i?this._sub?this._userManager.events._raiseUserSignedOut():this._userManager.events._raiseUserSignedIn():e.debug("no change in session detected, no event to raise")}catch(t){this._sub&&(e.debug("Error calling queryCurrentSigninSession; raising signed out event",t),this._userManager.events._raiseUserSignedOut())}},e||this._logger.throw(new Error("No user manager passed")),this._userManager.events.addUserLoaded(this._start),this._userManager.events.addUserUnloaded(this._stop),this._init().catch((e=>{this._logger.error(e)}))}async _init(){this._logger.create("_init");const e=await this._userManager.getUser();if(e)this._start(e);else if(this._userManager.settings.monitorAnonymousSession){const e=await this._userManager.querySessionStatus();if(e){const t={session_state:e.session_state,profile:e.sub&&e.sid?{sub:e.sub,sid:e.sid}:null};this._start(t)}}}},K=class{constructor(e){var t;this.id_token=e.id_token,this.session_state=null!=(t=e.session_state)?t:null,this.access_token=e.access_token,this.refresh_token=e.refresh_token,this.token_type=e.token_type,this.scope=e.scope,this.profile=e.profile,this.expires_at=e.expires_at,this.state=e.userState}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-v.getEpochTime()}set expires_in(e){void 0!==e&&(this.expires_at=Math.floor(e)+v.getEpochTime())}get expired(){const e=this.expires_in;if(void 0!==e)return e<=0}get scopes(){var e,t;return null!=(t=null==(e=this.scope)?void 0:e.split(" "))?t:[]}toStorageString(){return new w("User").create("toStorageString"),JSON.stringify({id_token:this.id_token,session_state:this.session_state,access_token:this.access_token,refresh_token:this.refresh_token,token_type:this.token_type,scope:this.scope,profile:this.profile,expires_at:this.expires_at})}static fromStorageString(e){return w.createStatic("User","fromStorageString"),new K(JSON.parse(e))}},D="oidc-client",J=class{constructor(){this._abort=new m("Window navigation aborted"),this._disposeHandlers=new Set,this._window=null}async navigate(e){const t=this._logger.create("navigate");if(!this._window)throw new Error("Attempted to navigate on a disposed window");t.debug("setting URL in window"),this._window.location.replace(e.url);const{url:i,keepOpen:s}=await new Promise(((i,s)=>{const r=r=>{var n;const o=r.data,a=null!=(n=e.scriptOrigin)?n:window.location.origin;if(r.origin===a&&(null==o?void 0:o.source)===D){try{const i=S.readParams(o.url,e.response_mode).get("state");if(i||t.warn("no state found in response url"),r.source!==this._window&&i!==e.state)return}catch(e){this._dispose(),s(new Error("Invalid response from window"))}i(o)}};window.addEventListener("message",r,!1),this._disposeHandlers.add((()=>window.removeEventListener("message",r,!1))),this._disposeHandlers.add(this._abort.addHandler((e=>{this._dispose(),s(e)})))}));return t.debug("got response from window"),this._dispose(),s||this.close(),{url:i}}_dispose(){this._logger.create("_dispose");for(const e of this._disposeHandlers)e();this._disposeHandlers.clear()}static _notifyParent(e,t,i=!1,s=window.location.origin){e.postMessage({source:D,url:t,keepOpen:i},s)}},V={location:!1,toolbar:!1,height:640},G="_blank",Q=60,Y=2,X=10,Z=class extends A{constructor(e){const{popup_redirect_uri:t=e.redirect_uri,popup_post_logout_redirect_uri:i=e.post_logout_redirect_uri,popupWindowFeatures:s=V,popupWindowTarget:r=G,redirectMethod:n="assign",redirectTarget:o="self",iframeNotifyParentOrigin:a=e.iframeNotifyParentOrigin,iframeScriptOrigin:c=e.iframeScriptOrigin,silent_redirect_uri:l=e.redirect_uri,silentRequestTimeoutInSeconds:d=X,automaticSilentRenew:u=!0,validateSubOnSilentRenew:h=!0,includeIdTokenInSilentRenew:g=!1,monitorSession:p=!1,monitorAnonymousSession:_=!1,checkSessionIntervalInSeconds:w=Y,query_status_response_type:f="code",stopCheckSessionOnError:m=!0,revokeTokenTypes:y=["access_token","refresh_token"],revokeTokensOnSignout:b=!1,includeIdTokenInSilentSignout:v=!1,accessTokenExpiringNotificationTimeInSeconds:S=Q,userStore:k}=e;if(super(e),this.popup_redirect_uri=t,this.popup_post_logout_redirect_uri=i,this.popupWindowFeatures=s,this.popupWindowTarget=r,this.redirectMethod=n,this.redirectTarget=o,this.iframeNotifyParentOrigin=a,this.iframeScriptOrigin=c,this.silent_redirect_uri=l,this.silentRequestTimeoutInSeconds=d,this.automaticSilentRenew=u,this.validateSubOnSilentRenew=h,this.includeIdTokenInSilentRenew=g,this.monitorSession=p,this.monitorAnonymousSession=_,this.checkSessionIntervalInSeconds=w,this.stopCheckSessionOnError=m,this.query_status_response_type=f,this.revokeTokenTypes=y,this.revokeTokensOnSignout=b,this.includeIdTokenInSilentSignout=v,this.accessTokenExpiringNotificationTimeInSeconds=S,k)this.userStore=k;else{const e="undefined"!=typeof window?window.sessionStorage:new E;this.userStore=new U({store:e})}}},ee=class extends J{constructor({silentRequestTimeoutInSeconds:e=X}){super(),this._logger=new w("IFrameWindow"),this._timeoutInSeconds=e,this._frame=ee.createHiddenIframe(),this._window=this._frame.contentWindow}static createHiddenIframe(){const e=window.document.createElement("iframe");return e.style.visibility="hidden",e.style.position="fixed",e.style.left="-1000px",e.style.top="0",e.width="0",e.height="0",e.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),window.document.body.appendChild(e),e}async navigate(e){this._logger.debug("navigate: Using timeout of:",this._timeoutInSeconds);const t=setTimeout((()=>this._abort.raise(new T("IFrame timed out without a response"))),1e3*this._timeoutInSeconds);return this._disposeHandlers.add((()=>clearTimeout(t))),await super.navigate(e)}close(){var e;this._frame&&(this._frame.parentNode&&(this._frame.addEventListener("load",(e=>{var t;const i=e.target;null==(t=i.parentNode)||t.removeChild(i),this._abort.raise(new Error("IFrame removed from DOM"))}),!0),null==(e=this._frame.contentWindow)||e.location.replace("about:blank")),this._frame=null),this._window=null}static notifyParent(e,t){return super._notifyParent(window.parent,e,!1,t)}},te=class{constructor(e){this._settings=e,this._logger=new w("IFrameNavigator")}async prepare({silentRequestTimeoutInSeconds:e=this._settings.silentRequestTimeoutInSeconds}){return new ee({silentRequestTimeoutInSeconds:e})}async callback(e){this._logger.create("callback"),ee.notifyParent(e,this._settings.iframeNotifyParentOrigin)}},ie=class extends J{constructor({popupWindowTarget:e=G,popupWindowFeatures:t={}}){super(),this._logger=new w("PopupWindow");const i=b.center({...V,...t});this._window=window.open(void 0,e,b.serialize(i))}async navigate(e){var t;null==(t=this._window)||t.focus();const i=setInterval((()=>{this._window&&!this._window.closed||this._abort.raise(new Error("Popup closed by user"))}),500);return this._disposeHandlers.add((()=>clearInterval(i))),await super.navigate(e)}close(){this._window&&(this._window.closed||(this._window.close(),this._abort.raise(new Error("Popup closed")))),this._window=null}static notifyOpener(e,t){if(!window.opener)throw new Error("No window.opener. Can't complete notification.");return super._notifyParent(window.opener,e,t)}},se=class{constructor(e){this._settings=e,this._logger=new w("PopupNavigator")}async prepare({popupWindowFeatures:e=this._settings.popupWindowFeatures,popupWindowTarget:t=this._settings.popupWindowTarget}){return new ie({popupWindowFeatures:e,popupWindowTarget:t})}async callback(e,t=!1){this._logger.create("callback"),ie.notifyOpener(e,t)}},re=class{constructor(e){this._settings=e,this._logger=new w("RedirectNavigator")}async prepare({redirectMethod:e=this._settings.redirectMethod,redirectTarget:t=this._settings.redirectTarget}){var i;this._logger.create("prepare");let s=window.self;"top"===t&&(s=null!=(i=window.top)?i:window.self);const r=s.location[e].bind(s.location);let n;return{navigate:async e=>{this._logger.create("navigate");const t=new Promise(((e,t)=>{n=t}));return r(e.url),await t},close:()=>{this._logger.create("close"),null==n||n(new Error("Redirect aborted")),s.stop()}}}},ne=class extends I{constructor(e){super({expiringNotificationTimeInSeconds:e.accessTokenExpiringNotificationTimeInSeconds}),this._logger=new w("UserManagerEvents"),this._userLoaded=new m("User loaded"),this._userUnloaded=new m("User unloaded"),this._silentRenewError=new m("Silent renew error"),this._userSignedIn=new m("User signed in"),this._userSignedOut=new m("User signed out"),this._userSessionChanged=new m("User session changed")}load(e,t=!0){super.load(e),t&&this._userLoaded.raise(e)}unload(){super.unload(),this._userUnloaded.raise()}addUserLoaded(e){return this._userLoaded.addHandler(e)}removeUserLoaded(e){return this._userLoaded.removeHandler(e)}addUserUnloaded(e){return this._userUnloaded.addHandler(e)}removeUserUnloaded(e){return this._userUnloaded.removeHandler(e)}addSilentRenewError(e){return this._silentRenewError.addHandler(e)}removeSilentRenewError(e){return this._silentRenewError.removeHandler(e)}_raiseSilentRenewError(e){this._silentRenewError.raise(e)}addUserSignedIn(e){return this._userSignedIn.addHandler(e)}removeUserSignedIn(e){this._userSignedIn.removeHandler(e)}_raiseUserSignedIn(){this._userSignedIn.raise()}addUserSignedOut(e){return this._userSignedOut.addHandler(e)}removeUserSignedOut(e){this._userSignedOut.removeHandler(e)}_raiseUserSignedOut(){this._userSignedOut.raise()}addUserSessionChanged(e){return this._userSessionChanged.addHandler(e)}removeUserSessionChanged(e){this._userSessionChanged.removeHandler(e)}_raiseUserSessionChanged(){this._userSessionChanged.raise()}},oe=class{constructor(e){this._userManager=e,this._logger=new w("SilentRenewService"),this._isStarted=!1,this._retryTimer=new v("Retry Silent Renew"),this._tokenExpiring=async()=>{const e=this._logger.create("_tokenExpiring");try{await this._userManager.signinSilent(),e.debug("silent token renewal successful")}catch(t){if(t instanceof T)return e.warn("ErrorTimeout from signinSilent:",t,"retry in 5s"),void this._retryTimer.init(5);e.error("Error from signinSilent:",t),this._userManager.events._raiseSilentRenewError(t)}}}async start(){const e=this._logger.create("start");if(!this._isStarted){this._isStarted=!0,this._userManager.events.addAccessTokenExpiring(this._tokenExpiring),this._retryTimer.addHandler(this._tokenExpiring);try{await this._userManager.getUser()}catch(t){e.error("getUser error",t)}}}stop(){this._isStarted&&(this._retryTimer.cancel(),this._retryTimer.removeHandler(this._tokenExpiring),this._userManager.events.removeAccessTokenExpiring(this._tokenExpiring),this._isStarted=!1)}},ae=class{constructor(e){this.refresh_token=e.refresh_token,this.id_token=e.id_token,this.session_state=e.session_state,this.scope=e.scope,this.profile=e.profile,this.data=e.state}},ce=class{constructor(e){this._logger=new w("UserManager"),this.settings=new Z(e),this._client=new z(e),this._redirectNavigator=new re(this.settings),this._popupNavigator=new se(this.settings),this._iframeNavigator=new te(this.settings),this._events=new ne(this.settings),this._silentRenewService=new oe(this),this.settings.automaticSilentRenew&&this.startSilentRenew(),this._sessionMonitor=null,this.settings.monitorSession&&(this._sessionMonitor=new B(this))}get events(){return this._events}get metadataService(){return this._client.metadataService}async getUser(){const e=this._logger.create("getUser"),t=await this._loadUser();return t?(e.info("user loaded"),this._events.load(t,!1),t):(e.info("user not found in storage"),null)}async removeUser(){const e=this._logger.create("removeUser");await this.storeUser(null),e.info("user removed from storage"),this._events.unload()}async signinRedirect(e={}){this._logger.create("signinRedirect");const{redirectMethod:t,...i}=e,s=await this._redirectNavigator.prepare({redirectMethod:t});await this._signinStart({request_type:"si:r",...i},s)}async signinRedirectCallback(e=window.location.href){const t=this._logger.create("signinRedirectCallback"),i=await this._signinEnd(e);return i.profile&&i.profile.sub?t.info("success, signed in subject",i.profile.sub):t.info("no subject"),i}async signinResourceOwnerCredentials({username:e,password:t,skipUserInfo:i=!1}){const s=this._logger.create("signinResourceOwnerCredential"),r=await this._client.processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:i,extraTokenParams:this.settings.extraTokenParams});s.debug("got signin response");const n=await this._buildUser(r);return n.profile&&n.profile.sub?s.info("success, signed in subject",n.profile.sub):s.info("no subject"),n}async signinPopup(e={}){const t=this._logger.create("signinPopup"),{popupWindowFeatures:i,popupWindowTarget:s,...r}=e,n=this.settings.popup_redirect_uri;n||t.throw(new Error("No popup_redirect_uri configured"));const o=await this._popupNavigator.prepare({popupWindowFeatures:i,popupWindowTarget:s}),a=await this._signin({request_type:"si:p",redirect_uri:n,display:"popup",...r},o);return a&&(a.profile&&a.profile.sub?t.info("success, signed in subject",a.profile.sub):t.info("no subject")),a}async signinPopupCallback(e=window.location.href,t=!1){const i=this._logger.create("signinPopupCallback");await this._popupNavigator.callback(e,t),i.info("success")}async signinSilent(e={}){var t;const i=this._logger.create("signinSilent"),{silentRequestTimeoutInSeconds:s,...r}=e;let n=await this._loadUser();if(null==n?void 0:n.refresh_token){i.debug("using refresh token");const e=new ae(n);return await this._useRefreshToken(e)}const o=this.settings.silent_redirect_uri;let a;o||i.throw(new Error("No silent_redirect_uri configured")),n&&this.settings.validateSubOnSilentRenew&&(i.debug("subject prior to silent renew:",n.profile.sub),a=n.profile.sub);const c=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:s});return n=await this._signin({request_type:"si:s",redirect_uri:o,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==n?void 0:n.id_token:void 0,...r},c,a),n&&((null==(t=n.profile)?void 0:t.sub)?i.info("success, signed in subject",n.profile.sub):i.info("no subject")),n}async _useRefreshToken(e){const t=await this._client.useRefreshToken({state:e,timeoutInSeconds:this.settings.silentRequestTimeoutInSeconds}),i=new K({...e,...t});return await this.storeUser(i),this._events.load(i),i}async signinSilentCallback(e=window.location.href){const t=this._logger.create("signinSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async signinCallback(e=window.location.href){const{state:t}=await this._client.readSigninResponseState(e);switch(t.request_type){case"si:r":return await this.signinRedirectCallback(e);case"si:p":return await this.signinPopupCallback(e);case"si:s":return await this.signinSilentCallback(e);default:throw new Error("invalid response_type in state")}}async signoutCallback(e=window.location.href,t=!1){const{state:i}=await this._client.readSignoutResponseState(e);if(i)switch(i.request_type){case"so:r":await this.signoutRedirectCallback(e);break;case"so:p":await this.signoutPopupCallback(e,t);break;case"so:s":await this.signoutSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async querySessionStatus(e={}){const t=this._logger.create("querySessionStatus"),{silentRequestTimeoutInSeconds:i,...s}=e,r=this.settings.silent_redirect_uri;r||t.throw(new Error("No silent_redirect_uri configured"));const n=await this._loadUser(),o=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:i}),a=await this._signinStart({request_type:"si:s",redirect_uri:r,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==n?void 0:n.id_token:void 0,response_type:this.settings.query_status_response_type,scope:"openid",skipUserInfo:!0,...s},o);try{const e=await this._client.processSigninResponse(a.url);return t.debug("got signin response"),e.session_state&&e.profile.sub?(t.info("success for subject",e.profile.sub),{session_state:e.session_state,sub:e.profile.sub,sid:e.profile.sid}):(t.info("success, user not authenticated"),null)}catch(e){if(this.settings.monitorAnonymousSession&&e instanceof k)switch(e.error){case"login_required":case"consent_required":case"interaction_required":case"account_selection_required":return t.info("success for anonymous user"),{session_state:e.session_state}}throw e}}async _signin(e,t,i){const s=await this._signinStart(e,t);return await this._signinEnd(s.url,i)}async _signinStart(e,t){const i=this._logger.create("_signinStart");try{const s=await this._client.createSigninRequest(e);return i.debug("got signin request"),await t.navigate({url:s.url,state:s.state.id,response_mode:s.state.response_mode,scriptOrigin:this.settings.iframeScriptOrigin})}catch(e){throw i.debug("error after preparing navigator, closing navigator window"),t.close(),e}}async _signinEnd(e,t){const i=this._logger.create("_signinEnd"),s=await this._client.processSigninResponse(e);i.debug("got signin response");return await this._buildUser(s,t)}async _buildUser(e,t){const i=this._logger.create("_buildUser"),s=new K(e);if(t){if(t!==s.profile.sub)throw i.debug("current user does not match user returned from signin. sub from signin:",s.profile.sub),new k({...e,error:"login_required"});i.debug("current user matches user returned from signin")}return await this.storeUser(s),i.debug("user stored"),this._events.load(s),s}async signoutRedirect(e={}){const t=this._logger.create("signoutRedirect"),{redirectMethod:i,...s}=e,r=await this._redirectNavigator.prepare({redirectMethod:i});await this._signoutStart({request_type:"so:r",post_logout_redirect_uri:this.settings.post_logout_redirect_uri,...s},r),t.info("success")}async signoutRedirectCallback(e=window.location.href){const t=this._logger.create("signoutRedirectCallback"),i=await this._signoutEnd(e);return t.info("success"),i}async signoutPopup(e={}){const t=this._logger.create("signoutPopup"),{popupWindowFeatures:i,popupWindowTarget:s,...r}=e,n=this.settings.popup_post_logout_redirect_uri,o=await this._popupNavigator.prepare({popupWindowFeatures:i,popupWindowTarget:s});await this._signout({request_type:"so:p",post_logout_redirect_uri:n,state:null==n?void 0:{},...r},o),t.info("success")}async signoutPopupCallback(e=window.location.href,t=!1){const i=this._logger.create("signoutPopupCallback");await this._popupNavigator.callback(e,t),i.info("success")}async _signout(e,t){const i=await this._signoutStart(e,t);return await this._signoutEnd(i.url)}async _signoutStart(e={},t){var i;const s=this._logger.create("_signoutStart");try{const r=await this._loadUser();s.debug("loaded current user from storage"),this.settings.revokeTokensOnSignout&&await this._revokeInternal(r);const n=e.id_token_hint||r&&r.id_token;n&&(s.debug("setting id_token_hint in signout request"),e.id_token_hint=n),await this.removeUser(),s.debug("user removed, creating signout request");const o=await this._client.createSignoutRequest(e);return s.debug("got signout request"),await t.navigate({url:o.url,state:null==(i=o.state)?void 0:i.id})}catch(e){throw s.debug("error after preparing navigator, closing navigator window"),t.close(),e}}async _signoutEnd(e){const t=this._logger.create("_signoutEnd"),i=await this._client.processSignoutResponse(e);return t.debug("got signout response"),i}async signoutSilent(e={}){var t;const i=this._logger.create("signoutSilent"),{silentRequestTimeoutInSeconds:s,...r}=e,n=this.settings.includeIdTokenInSilentSignout?null==(t=await this._loadUser())?void 0:t.id_token:void 0,o=this.settings.popup_post_logout_redirect_uri,a=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:s});await this._signout({request_type:"so:s",post_logout_redirect_uri:o,id_token_hint:n,...r},a),i.info("success")}async signoutSilentCallback(e=window.location.href){const t=this._logger.create("signoutSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async revokeTokens(e){const t=await this._loadUser();await this._revokeInternal(t,e)}async _revokeInternal(e,t=this.settings.revokeTokenTypes){const i=this._logger.create("_revokeInternal");if(!e)return;const s=t.filter((t=>"string"==typeof e[t]));if(s.length){for(const t of s)await this._client.revokeToken(e[t],t),i.info(`${t} revoked successfully`),"access_token"!==t&&(e[t]=null);await this.storeUser(e),i.debug("user stored"),this._events.load(e)}else i.debug("no need to revoke due to no token(s)")}startSilentRenew(){this._logger.create("startSilentRenew"),this._silentRenewService.start()}stopSilentRenew(){this._silentRenewService.stop()}get _userStoreKey(){return`user:${this.settings.authority}:${this.settings.client_id}`}async _loadUser(){const e=this._logger.create("_loadUser"),t=await this.settings.userStore.get(this._userStoreKey);return t?(e.debug("user storageString loaded"),K.fromStorageString(t)):(e.debug("no user storageString"),null)}async storeUser(e){const t=this._logger.create("storeUser");if(e){t.debug("storing user");const i=e.toStorageString();await this.settings.userStore.set(this._userStoreKey,i)}else this._logger.debug("removing user"),await this.settings.userStore.remove(this._userStoreKey)}async clearStaleState(){await this._client.clearStaleState()}};class le{constructor(e={path:"/"}){var t,i,s;s=void 0,(i="defaultAttributes")in(t=this)?Object.defineProperty(t,i,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[i]=s,this.defaultAttributes=e}setItem(e,t,i={}){const s={...this.defaultAttributes,...i};let r=encodeURIComponent(e)+"="+encodeURIComponent(t);if(s.expires){if("number"==typeof s.expires){const e=new Date;e.setTime(e.getTime()+24*s.expires*60*60*1e3),s.expires=e}r+="; expires="+s.expires.toUTCString()}s.path&&(r+="; path="+s.path),s.domain&&(r+="; domain="+s.domain),s.secure&&(r+="; secure"),s.sameSite&&(r+="; SameSite="+s.sameSite),document.cookie=r}getItem(e){const t=(document.cookie?document.cookie.split("; "):[]).find((t=>t.startsWith(`${encodeURIComponent(e)}=`)));return t?decodeURIComponent(t.split("=")[1]):null}removeItem(e){this.setItem(e,"",{expires:-1})}clear(){const e=document.cookie.split(";");for(const t of e){const e=t.indexOf("="),i=e>-1?t.substring(0,e):t;document.cookie=i+"=;expires=Thu, 01 Jan 1970 00:00:00 GMT"}}}var de=i(65),ue=i.n(de);function he(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}const ge={secure:!0,path:"/",domain:(pe=window.location.hostname,pe.replace(/^www\./,"").split(".").slice(-2).join(".")),sameSite:"None",expires:365};var pe;class _e{constructor(e,t){he(this,"pluginConfig",void 0),he(this,"cookieStoreKey",void 0),he(this,"cookieStorage",void 0),this.pluginConfig=t,this.cookieStoreKey=e,this.cookieStorage=new le(ge),ue().debug(`LocalStorageCookieFallback: extendLoginToSubdomains: ${this.pluginConfig.extendLoginToSubdomains}`)}static getInstance(e){if(null===_e.instance){const t=`oidc.user:${e.oidcConf.authority}`;_e.instance=new _e(t,e)}return _e.instance}static clearInstance(){_e.instance=null}getItem(e){let t=localStorage.getItem(e);return this.pluginConfig.extendLoginToSubdomains&&null===t?(t=this.cookieStorage.getItem(this.cookieStoreKey),t&&localStorage.setItem(e,t)):this.pluginConfig.extendLoginToSubdomains&&t&&this.cookieStorage.setItem(this.cookieStoreKey,t),t}setItem(e,t){localStorage.setItem(e,t),this.pluginConfig.extendLoginToSubdomains&&this.cookieStorage.setItem(this.cookieStoreKey,t)}removeItem(e){localStorage.removeItem(e),this.cookieStorage.removeItem(this.cookieStoreKey)}clear(){localStorage.clear(),this.cookieStorage.removeItem(this.cookieStoreKey)}key(e){return localStorage.key(e)}get length(){return localStorage.length}}he(_e,"instance",null);function we(e,t={}){const i={...t};return i.headers={...i.headers,"Anon-App-Version":"1.8.43"},fetch(e,i)}function fe(e,t){const i={method:"GET",headers:{"Content-Type":"application/json",acc_uuid:t,url:encodeURIComponent(window.location.href)}};we(`${e.idwServicesConf.idwMetricsCollector}/ok`,i).catch((e=>{console.warn("Anonymised tag: failed to GET metrics/collect/ok",e)}))}async function me(e){try{return d(e).sub}catch(e){return console.warn("Anonymised tag: failed to parse JWT token",e),null}}function ye(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class be{constructor(e){ye(this,"pluginConfig",void 0),ye(this,"userManager",void 0),ye(this,"baseOidcConf",void 0),ye(this,"allowedHealthCheckTime",1750),this.pluginConfig=e;const t=_e.getInstance(e),i=this.pluginConfig.oidcConf;this.baseOidcConf={...i,automaticSilentRenew:!1,userStore:new U({store:t})};const s=Number(localStorage.getItem("idw-renew"));s&&s>0&&(this.baseOidcConf.accessTokenExpiringNotificationTimeInSeconds=s),this.userManager=new ce(this.baseOidcConf)}isLoginExceptionPage(){const e=this.pluginConfig.loginExceptionPages?.some((e=>window.location.href.includes(e.toLocaleLowerCase())));return e}isLoginInclusionPage(){return!this.pluginConfig.loginInclusionPages||this.pluginConfig.loginInclusionPages.some((e=>window.location.href.includes(e.toLocaleLowerCase())))}async collectMetrics(e,t=!1){if(t)fe(this.pluginConfig,e);else{const t=await me(e);fe(this.pluginConfig,t)}}}const ve=(e,t)=>{const i=new URL(e),s=new URLSearchParams(i.search);for(const e in t)void 0!==t[e]&&s.set(e,t[e]);return i.search=s.toString(),i.hash="",i.toString()};async function Se(e){const t={method:"GET",headers:{"Content-Type":"application/json"}};try{const i=performance.now(),s=await we(`${e.idwServicesConf.idwHealthCheckUrl}`,t),r=performance.now(),n=Math.round(r-i);ue().debug(`Health check from ${e.idwServicesConf.idwHealthCheckUrl}, Time: ${n}ms, response.url: ${s?.url}`);return s?.ok&&(!s?.url||s?.url===e.idwServicesConf.idwHealthCheckUrl)?n:null}catch(e){return null}}const ke="anonUserSignedIn",Te=()=>{try{let e;"function"==typeof Event?e=new Event(ke):(e=document.createEvent("Event"),e.initEvent(ke,!1,!1)),window.dispatchEvent(e)}catch(e){ue().error(`Failed to dispatch sign-in event: ${e}`)}};function Ie(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class Ce extends be{constructor(e){super(e),Ie(this,"loginLock",void 0),Ie(this,"pageUnloading",void 0),Ie(this,"visibilitychangeSubscribed",void 0),this.userManager.events.addAccessTokenExpired((()=>{ue().debug("token expired, will queue OOF"),this.queueLogin()})),this.userManager.events.addAccessTokenExpiring((()=>{ue().debug("token expiring, will queue OOF"),this.queueLogin()})),ue().debug("RedirectPageLoginManager initialized")}async queueLogin(){const e=this.isImmediateLoginPage();let t=this.isLoginExceptionPage(),i=this.isLoginInclusionPage();e&&!t&&i?this.tryLogin():(ue().debug("queue OOF"),window.addEventListener("beforeunload",(()=>{this.pageUnloading=!0})),this.visibilitychangeSubscribed?ue().debug("visibilitychange already added, will not subscribe once more"):(ue().debug("addEventListener visibilitychange"),this.visibilitychangeSubscribed=!0,addEventListener("visibilitychange",(()=>{t=this.isLoginExceptionPage(),i=this.isLoginInclusionPage(),"hidden"===document.visibilityState&&!t&&i&&this.tryLogin()}))))}isImmediateLoginPage(){const e=this.pluginConfig.immediateLoginPages?.some((e=>window.location.href.includes(e.toLocaleLowerCase())));return e}async tryLogin(t=window.location.href){if(this.loginLock||this.pageUnloading)return;const i=await Se(this.pluginConfig);if(i&&i<=this.allowedHealthCheckTime)await this.login(t);else if(i){ue().warn(`health check took ${i}ms, network connection is too slow. Will not do OOF`);const t={method:"GET",headers:{"Content-Type":"application/json",acc_uuid:window.localStorage.getItem(e.idwOutdated),url:encodeURIComponent(window.location.href),health_check_time:i.toString()}};we(`${this.pluginConfig.idwServicesConf.idwMetricsCollector}/debug/health`,t).catch((e=>{console.warn("Anonymised tag: failed to GET metrics/collect/debug/health",e)}))}else ue().warn("health check has failed, will not do OOF")}async login(t){if(this.loginLock)return;if(this.loginLock=!0,window.location.search.includes("callback=in"))return void ue().debug("terminate an attempt to OOF during the callback redirect");window.localStorage.setItem("idw-signin-from",t),window.sessionStorage.setItem(e.idwScrollY,window.scrollY.toString());const i={...this.baseOidcConf,redirect_uri:ve(t,{callback:"in"})},s=window.localStorage.getItem(e.idwOutdated);s&&(i.extraQueryParams={outdated:s}),ue().debug("update oidcConf.redirect_uri:",i.redirect_uri),this.userManager=new ce(i),ue().debug("start OOF");try{await this.userManager.signinRedirect({state:{signInFrom:window.location.href}})}catch(e){ue().warn(`OOF error: ${e}`)}}async getUser(){return this.userManager.getUser()}static async handleCallback(t){let i=!1;const s=_e.getInstance(t),r={...t.oidcConf,automaticSilentRenew:!1,userStore:new U({store:s})},n=new ce(r);try{const s=await n.signinCallback();if(i=!!s,s&&s.expires_in){const e=Math.round(s.expires_in/3).toString();window.localStorage.setItem("idw-renew",e)}if(s){const i=await me(s.access_token);fe(t,i),localStorage.setItem(e.idwOutdated,i),Te()}}catch(e){fe(t,"Signin callback error"),console.error("Anonymised tag: OOF callback error",e)}finally{console.debug("Anonymised tag: Signin callback done")}return i}}class Ee{static async waitForConfig(){return window._anonymised_tag?.pluginConfig&&window._anonymised_tag?.isTagVerified?{pluginConfig:window._anonymised_tag.pluginConfig,isTagVerified:window._anonymised_tag.isTagVerified}:new Promise(((e,t)=>{const i=setTimeout((()=>{t(new Error("Timeout waiting for shared configuration"))}),this.MAX_WAIT_TIME),s=setInterval((()=>{window._anonymised_tag?.pluginConfig&&window._anonymised_tag?.isTagVerified&&(clearTimeout(i),clearInterval(s),e({pluginConfig:window._anonymised_tag.pluginConfig,isTagVerified:window._anonymised_tag.isTagVerified}))}),100)}))}}var xe,Re,Ue;function Ae(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}Ue=1e4,(Re="MAX_WAIT_TIME")in(xe=Ee)?Object.defineProperty(xe,Re,{value:Ue,enumerable:!0,configurable:!0,writable:!0}):xe[Re]=Ue;class Oe{static async detect(e){return new Promise((t=>{let i=!1,s=null;const r=(e,r)=>{i||(i=!0,(e=>{window.removeEventListener("message",n,!1),clearTimeout(e),s&&Oe.cleanupIframe(s)})(r),t(e))},n=e=>{if(i||"cookie-test"!==e.data?.type)return;const t=e.data.enabled;ue().debug("3PC test result:",t),r(t,o)};window.addEventListener("message",n,!1);const o=setTimeout((()=>{ue().error("3PC test timed out"),r(!1,o)}),this.DETECTION_TIMEOUT_MS);s=this.createDetectionIframe(e)}))}static createDetectionIframe(e){const t=document.createElement("iframe");return t.style.display="none",t.src=`${e}${Oe.IFRAME_CHECK_PATH}`,document.body.appendChild(t),t}static cleanupIframe(e){try{e.remove()}catch(e){ue().error("Error cleaning up 3PC detection iframe:",e)}}}Ae(Oe,"DETECTION_TIMEOUT_MS",5e3),Ae(Oe,"IFRAME_CHECK_PATH","/light/check3pc.html");class Pe{async getUser(){return ue().debug("DummyLoginManager.getUser called"),null}queueLogin(){ue().debug("DummyLoginManager.queueLogin called")}}function Me(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}const Le=new class{constructor(){Me(this,"authorizationUrl",void 0),Me(this,"client",void 0)}removeRedundantOidcRecords(){Object.keys(localStorage).filter((e=>e.startsWith("oidc.")&&!e.startsWith("oidc.user"))).forEach((e=>localStorage.removeItem(e)))}async prepareAuthenticationListener(e,t,i,s){await this.generateAuthorizationUrl(e,t,i)&&this.registerAuthResultListener(s)}openAuthTab(){if(this.authorizationUrl?.url){const e=window.open(this.authorizationUrl.url,"_blank");return ue().debug(`is new tab opened: ${!!e}`),e}return null}openAuthIframe(){if(this.authorizationUrl?.url){ue().debug(`Opening auth iframe with URL: ${this.authorizationUrl.url}`);const e=document.createElement("iframe");e.style.display="none",e.src=this.authorizationUrl.url,document.body.appendChild(e)}}async generateAuthorizationUrl(e,t,i){try{const s=await e.getUser();if(!s||s.expired){const e="IFL"===t?"experiment/silent-ifl/auth":"experiment/no-oof-poc/auth";return this.client=new z({...i.oidcConf,metadata:{...i.oidcConf.metadata,authorization_endpoint:`${i.oidcConf.metadata.issuer}/${e}`}}),this.authorizationUrl=await this.client.createSigninRequest({}),ue().debug(`authorizationUrl registered: ${this.authorizationUrl?.url}`),!!this.authorizationUrl}}catch(e){return ue().warn(`New tab auth error: cannot generate auth URL ${e}`),!1}}registerAuthResultListener(e){window.addEventListener("message",(async t=>{if("get-redirect-url"===t.data?.type)try{ue().debug(`received 'get-redirect-url' message: ${JSON.stringify(t.data)}`);const i=await this.client.processSigninResponse(t.data.url);e(i),this.removeRedundantOidcRecords()}catch(t){ue().warn(`New tab auth error: ${t}`),e(null)}}),!1)}};class Ne{static detectDevice(){if(navigator.userAgentData?.mobile)return"mobile";const e=[this.checkUserAgent,this.checkScreenSize,this.checkTouchPoints,this.checkOrientation];return e.filter((e=>e())).length>=Math.ceil(e.length/2)?"mobile":"desktop"}static checkUserAgent(){const e=navigator.userAgent.toLowerCase();return["android","iphone","ipad","ipod","blackberry","windows phone","opera mini","mobile","tablet","mobi"].some((t=>e.includes(t)))}static checkScreenSize(){return window.innerWidth<=768}static checkTouchPoints(){return navigator.maxTouchPoints>1}static checkOrientation(){return window.innerHeight>window.innerWidth}static detectBrowser(){const e=navigator.userAgent.toLowerCase();return e.includes("chrome")&&!e.includes("edg")&&!e.includes("opr")||e.includes("crios")?"chrome":e.includes("edg")||e.includes("edge")?"edge":e.includes("firefox")||e.includes("fxios")?"firefox":!e.includes("safari")||e.includes("chrome")||e.includes("crios")||e.includes("fxios")||e.includes("edg")||e.includes("edge")||e.includes("opt")?e.includes("opr")||e.includes("opera")||e.includes("opera mini")||e.includes("opt")?"opera":e.includes("trident")||e.includes("msie")?"ie":"other":"safari"}}function qe(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}!function(e,t,i){t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i}(Ne,"isWebView",(()=>{const e=String(navigator.userAgent||navigator.vendor||(window.opera??"")),t=navigator.standalone,i=/iP(hone|od|ad)/.test(e)&&!/Safari/.test(e)&&!0!==t,s=/Android/.test(e)&&(/wv/.test(e)||/Version\/[\d.]+/.test(e)||!!window.JSInterface||!!window.Android),r=!!window.ReactNativeWebView||!!window.Capacitor||!!window.Cordova;return i||s||r})());class je extends be{constructor(e){super(e),qe(this,"events",["click"]),qe(this,"browserType",void 0),qe(this,"isMobile",void 0),qe(this,"isChrome",void 0),qe(this,"isOpera",void 0),qe(this,"hrefTo",null),qe(this,"loginTimeoutId",null),qe(this,"handleUserInteractionForAuth",(e=>{const t=e.target,i=t?.closest("a");ue().debug(`Try to initiate NTL on event ${e.type}`),i&&i.href&&(e.preventDefault(),this.hrefTo=i.href),this.initiateAuthenticationFlow();const s=4*this.allowedHealthCheckTime;this.loginTimeoutId=setTimeout((()=>{this.hrefTo&&(ue().debug(`Redirecting to href: ${this.hrefTo}`),window.location.href=this.hrefTo,this.hrefTo=null)}),s)})),this.isMobile="mobile"===Ne.detectDevice(),this.isMobile&&Le.prepareAuthenticationListener(this.userManager,"NTL",e,this.processAuthenticationResponse.bind(this)),this.browserType=Ne.detectBrowser(),this.isChrome="chrome"===this.browserType,this.isOpera="opera"===this.browserType,this.userManager.events.addAccessTokenExpired((()=>{ue().debug("token expired, will queue New Tab Login"),this.subscribeToUserInteractionEvents()})),this.userManager.events.addAccessTokenExpiring((()=>{ue().debug("token expiring, will queue New Tab Login"),this.subscribeToUserInteractionEvents()})),ue().debug(`NewTabLoginManager initialized: isMobile=${this.isMobile}, browserType=${this.browserType}`)}async queueLogin(){Ne.isWebView&&this.isMobile?ue().debug("New Tab Login is disabled for WebView mobile apps"):this.isMobile?this.isOpera?ue().debug("New Tab Login is temporarily disabled for Opera browser"):(this.isChrome||(ue().debug("Queue NTL"),this.initiateAuthenticationFlow()),this.subscribeToUserInteractionEvents()):ue().debug("New Tab Login is temporarily disabled for desktop browsers")}async subscribeToUserInteractionEvents(){if(this.isMobile){const e=await Se(this.pluginConfig);e&&e<=this.allowedHealthCheckTime?(this.events.forEach((e=>{document.addEventListener(e,this.handleUserInteractionForAuth,{once:!0})})),ue().debug("Subscribed to user interaction events for retry login")):ue().debug(`Health check failed or took too long: ${e}ms, \n not subscribing to user interaction events to retry login`)}}initiateAuthenticationFlow(){Le.openAuthTab()}async processAuthenticationResponse(e){try{if(ue().debug(`NTL SigninResponse received: ${JSON.stringify(e)}`),e){const t=new K(e);await this.userManager.storeUser(t),Te(),this.loginTimeoutId&&clearTimeout(this.loginTimeoutId),this.loginTimeoutId=null,this.events.forEach((e=>{document.removeEventListener(e,this.handleUserInteractionForAuth)})),this.collectMetrics(t.access_token)}else this.collectMetrics("New tab auth error: Authorization Code Response was not generated, register fallback click event",!0)}catch(e){ue().warn(`New tab login error: ${e}`),this.collectMetrics(`New tab login error: ${e}`,!0)}finally{this.hrefTo&&(window.location.href=this.hrefTo,this.hrefTo=null)}}async getUser(){return this.userManager.getUser()}}class He extends be{constructor(e){super(e),Le.prepareAuthenticationListener(this.userManager,"IFL",e,this.processAuthenticationResponse.bind(this)),this.userManager.events.addAccessTokenExpired((()=>{ue().debug("token expired, will clear oidc records"),setTimeout((()=>{Le.removeRedundantOidcRecords()}),3e3)})),ue().debug("IframeLoginManager initialized")}async queueLogin(){ue().debug("Queue Iframe Login"),setTimeout((()=>{Le.openAuthIframe()}),500)}async processAuthenticationResponse(e){try{if(ue().debug("Iframe SigninResponse received: ",e),e){const t=new K(e);await this.userManager.storeUser(t),Te(),this.collectMetrics(t.access_token)}else this.collectMetrics("Iframe auth error: Authorization Code Response was not generated, register fallback click event",!0)}catch(e){ue().warn(`Iframe login error: ${e}`),this.collectMetrics(`Iframe login error: ${e}`,!0)}}async getUser(){return this.userManager.getUser()}}class Fe{static async detect3PC(e){return Oe.detect(e)}static async createLoginManager(e){if(!e.loginRedirect&&!e.loginInNewTab&&!e.iframeLogin)return ue().debug("Login disabled - using DummyLoginManager"),new Pe;if(e.loginRedirect&&e.loginInNewTab&&ue().warn("Both loginRedirect and loginInNewTab enabled without iframeLogin. Invalid config"),e.iframeLogin){if(await Fe.canUseIframeLogin(e))return ue().debug("Using IframeLoginManager - explicitly enabled and supported"),new He(e)}return Fe.createRedirectBasedLoginManager(e)}static async canUseIframeLogin(e){const t=Ne.detectBrowser();if("safari"===t||"firefox"===t)return ue().debug(`Iframe login not supported in ${t} browser`),!1;return!!await Fe.detect3PC(e.idwServicesConf.anonmStaticDomain)||(ue().debug("Iframe login not supported - 3PC not available"),!1)}static createRedirectBasedLoginManager(e){return e.loginRedirect?(ue().debug("Using RedirectPageLoginManager - explicitly enabled"),new Ce(e)):e.loginInNewTab?(ue().debug("Using NewTabLoginManager - explicitly enabled"),new je(e)):(ue().debug("No redirect-based login configured - using DummyLoginManager"),new Pe)}static async waitForConfigAndCreateLoginManager(){try{const{pluginConfig:e}=await Ee.waitForConfig();return Fe.createLoginManager(e)}catch(e){return ue().error("Failed to load shared configuration, falling back to DummyLoginManager:",e),new Pe}}}function $e(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}const We=new class{constructor(){$e(this,"loginManager",null),$e(this,"initPromise",void 0),Ee.waitForConfig().then((({pluginConfig:e})=>{this.handleCallback(e)})),this.initPromise=this.initializeLoginManager(),console.debug("AuthModule initialized")}async initializeLoginManager(){try{this.loginManager=await Fe.waitForConfigAndCreateLoginManager()}catch(e){console.warn("Failed to initialize LoginManager with shared config:",e)}}async queueLogin(){await this.initPromise,this.loginManager?this.loginManager.queueLogin():console.warn("LoginManager not initialized, cannot queue login")}async getUser(){return await this.initPromise,this.loginManager?this.loginManager.getUser():(console.warn("LoginManager not initialized, cannot get user"),null)}async handleCallback(t){if(window.location.search.includes("callback=in")){const i=document.createElement("meta");i.name="robots",i.content="noindex",document.head.appendChild(i);if(!await Ce.handleCallback(t))return;const s=window.localStorage.getItem("idw-signin-from")??"/";console.debug(`replacing url back to ${s}`),window.history.replaceState({},"",s),sessionStorage.setItem(e.isOofUrl,"true");const r=window.sessionStorage.getItem(e.idwScrollY);r&&setTimeout((()=>{window.scrollTo(0,Number(r)),window.sessionStorage.removeItem(e.idwScrollY)}),50)}}};window._anonymised_tag=window._anonymised_tag||{},window._anonymised_tag.auth=We})()})();